package opensky.dbcache.dbvp.core;

import net.sf.jsqlparser.expression.Alias;
import net.sf.jsqlparser.expression.ExpressionVisitor;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.Pivot;
import net.sf.jsqlparser.util.deparser.SelectDeParser;
import opensky.dbcache.dbvp.api.ErrorMode;
import opensky.dbcache.dbvp.api.FullTableName;
import opensky.dbcache.dbvp.api.SqlvpException;

import java.util.Map;

/**
 * Select类型的Sql解析处理
 *
 * @Author zhenggm
 * @Date 2017/9/21 下午4:04
 */
public class DBSelectDeParser extends SelectDeParser {

    private ErrorMode mode;
    Map<String, Object> context;

    public DBSelectDeParser(ExpressionVisitor expressionVisitor, StringBuilder buffer, ErrorMode mode, Map<String, Object> context) {
        super(expressionVisitor, buffer);
        this.mode = mode;
        this.context = context;
    }

    @Override
    public void visit(Table tableName) {
        String schema = tableName.getSchemaName();
        String table = tableName.getName();
        FullTableName fullTableName = new FullTableName(schema, table);

        TableChangerImpl tableChanger = new TableChangerImpl(mode);
        // 将table置入RuleSet进行替换
        fullTableName = tableChanger.change(fullTableName, context);

        if (fullTableName ==null){
            throw new SqlvpException("table is null");
        }
        tableName.setSchemaName(fullTableName.getSchema());
        tableName.setName(fullTableName.getTable());
        StringBuilder buffer = getBuffer();

        buffer.append(tableName.getFullyQualifiedName());
        Pivot pivot = tableName.getPivot();
        if (pivot != null) {
            pivot.accept(this);
        }
        Alias alias = tableName.getAlias();
        if (alias != null) {
            buffer.append(alias);
        }
    }
}
